from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
from app.api import api_router
import logging

logger = logging.getLogger(__name__)

# 创建 FastAPI 应用
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description="一个现代化的个人知识管理系统"
)

# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.BACKEND_CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 添加请求日志中间件（用于调试）
@app.middleware("http")
async def log_requests(request: Request, call_next):
    auth_header = request.headers.get("authorization")
    logger.info(f"[请求] {request.method} {request.url.path} - Authorization: {auth_header[:50] if auth_header else 'None'}")
    response = await call_next(request)
    logger.info(f"[响应] {request.method} {request.url.path} - Status: {response.status_code}")
    return response

# 注册路由
app.include_router(api_router)


@app.get("/")
async def root():
    """根路径"""
    return {
        "message": "欢迎使用智能个人知识库系统",
        "version": settings.APP_VERSION,
        "docs": "/docs"
    }


@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=settings.DEBUG
    )

